package io.gitee.thinkbungee.annotation.condition;

import io.gitee.thinkbungee.constant.SatelliteConstant;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

/**
 * 是否激活某个组件的条件
 *
 * @author chenyichang
 * @since 2022/5/27
 */
public class OnComponentCondition extends SpringBootCondition {

    /**
     * 组件前缀
     */
    private String prefix = SatelliteConstant.Component.PREFIX;

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Map<String, Object> annotationAttributes =
                metadata.getAnnotationAttributes(ConditionOnComponent.class.getName());
        //组件名称
        String componentName = String.valueOf(annotationAttributes.get("value"));

        ConditionOutcome endPointOutcome = getEndPointOutcome(context, componentName);
        if (endPointOutcome != null) {
            return endPointOutcome;
        }
        return ConditionOutcome.noMatch(ConditionMessage.of("not load"));
    }

    private ConditionOutcome getEndPointOutcome(ConditionContext context, String componentName) {
        Environment environment = context.getEnvironment();
        String enableProperty = this.prefix + componentName + SatelliteConstant.Component.ENABLE;
        if (environment.containsProperty(enableProperty)) {
            Boolean match = environment.getProperty(enableProperty, Boolean.class, true);
            return new ConditionOutcome(match, ConditionMessage.forCondition(ConditionOnComponent.class)
                    .because(enableProperty + " is " + match));
        }
        return null;
    }
}
